/* =====================================================================================
 *
 *       Filename:  MeshObject.cpp
 *
 *    Description:  implementation of MeshObject.h
 *
 *        Version:  1.0
 *        Created:  05/31/2011 08:45:41 PM
 *       Compiler:  gcc
 *
 *         Author:  Toth Tamas (Osiris), osiris996@gamil.com
 *
 * =====================================================================================
 */

#include "MeshObject.h"
#include <cstring>
#include <stdio.h>
#include <stdlib.h>

MeshObject::MeshObject(const char *objectName, unsigned char *c, float *m){
  _n_qfaces = 0; 
  _n_tfaces = 0;
  if (m){
      for (int i = 0; i < 4 * 4; ++i)
      {
         _m[i] = m[i];
      }
  }
  else{
    for (int i = 0; i < 4 * 4; ++i)
    {
      _m[i] = 0.0;
    }
     _m[0] = 1.0;
     _m[5] = 1.0;
     _m[10] = 1.0;
     _m[15] = 1.0;
  }
  color[0] = c[0];
  color[1] = c[1];
  color[2] = c[2];

  char fileName[256];
  strcpy(fileName,"Objects/");
  strcat(fileName,objectName);
  strcat(fileName,".obj");
  loadObjectFromFile(fileName);
}

MeshObject::~MeshObject(){
  delete _verts;
  _qfaces.~QVector();
  _tfaces.~QVector();
}

void MeshObject::loadObjectFromFile(char *fileName){
  FILE* file = fopen(fileName,"r");
  int e;
  if(file == NULL){
    printf("%s not Found!\n",fileName);
    return;
  }
  int n;
  e = fscanf(file,"%i\n",&n);
  _verts = (float**) malloc(n*3*sizeof(float));
  
  for(int i = 0; i < n; i++){
    _verts[i] = new float[3];
    e = fscanf(file,"%f %f %f\n", &_verts[i][0], &_verts[i][1], &_verts[i][2]);
  }
  
  e = fscanf(file,"%i\n",&n);
  char* buffer = new char [255];
  for(int i = 0; i < n; i++){
    int *v = new int[4];
    if(fgets(buffer, 255, file)== NULL){
      printf("%s reading error",fileName);
    };
    e = sscanf(buffer,"%d %d %d %d\n", &v[0], &v[1], &v[2], &v[3]);
    if(e == 4){
      _qfaces.append(v);
      _n_qfaces++;
    }else{
      if(e == 3){
        _tfaces.append(v);
        _n_tfaces++;
      }
    }
  } 
    

  printf("%s loaded...\n",fileName);
}

void MeshObject::renderInLocalFrame() const {
  int *v;
  glBegin(GL_QUADS);
  glColor3ubv(color);
  for(int i = 0; i < _n_qfaces; i++){
    v=_qfaces[i]; 
    glVertex3fv(_verts[v[0]]);
    glVertex3fv(_verts[v[1]]);
    glVertex3fv(_verts[v[2]]);
    glVertex3fv(_verts[v[3]]);
  }
  glEnd();
  glBegin(GL_TRIANGLES);
  glColor3ubv(color);
  for(int i = 0; i < _n_tfaces; i++){
    v=_tfaces[i];
    glVertex3fv(_verts[v[0]]);
    glVertex3fv(_verts[v[1]]);
    glVertex3fv(_verts[v[2]]);
  }
  glEnd();
}
